import config from "@/config/index.js";
const baseUrl = config.baseUrl;
/**
 * 请求数据封装方法
 * @param method 请求方式 GET POST PUT
 * @param url 请求地址（login/login）
 * @param data 请求对象
 * @param loading 是否展示loading
 * @param loadingTitle 展示loading文字
 * @returns {Promise<unknown>}
 */
function fetch(method, url, data, loading, loadingTitle, paramsUrl) {
	return new Promise((resolve, reject) => {
		//显示加载动画
		if (loading) {
			uni.showLoading({
				title: loadingTitle,
				mask: true,
			});
		}
		//添加params,浅拷贝
		const params = {};
		Object.assign(params, data);
		//获取Authorization
		let token = uni.getStorageSync("token") ? uni.getStorageSync("token") : "";
		uni.request({
			url,
			method,
			data: params,
			header: {
				// 数据被编码为名称/值对
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
				"authoriztion": token
			},
			success: res => {
				// console.log(res.data, '----code????')
				let code = Number(res.data.code);
				let message = res.data.msg || '';
				if (loading) {
					setTimeout(() => {
						if (code == 200) {
							resolve(res.data);
						}else {
							uni.showToast({
								title: message,
								duration: 2000,
								icon: 'none',
								mask: true
							});
							resolve(res.data);
						}
					}, 1500);
				} else {
					if (code == 200) {
						resolve(res.data);
					}else {
						uni.showToast({
							icon: 'none',
							duration: 3000,
							title: message
						});
						resolve(res.data);
					}
				}
			},
			fail: err => {
				reject(err);
			},
			complete: () => {
				setTimeout(function() {
					uni.stopPullDownRefresh(); //停止下拉刷新动画
				}, 1000);
				if (loading) {
					setTimeout(() => {
						uni.hideLoading();
					}, 1000)
				}
			},
		});
	});
}
export default {
	get(url, params, loading, loadingTitle) {
		return fetch("GET", baseUrl + url, params, loading, loadingTitle);
	},
	post(url, params, loading, loadingTitle) {
		return fetch("POST", baseUrl + url, params, loading, loadingTitle);
	},
	put(url, params, loading, loadingTitle) {
		return fetch("PUT", baseUrl + url, params, loading, loadingTitle);
	},
	delete(url, params, loading, loadingTitle) {
		return fetch("DELETE", baseUrl + url, params, loading, loadingTitle);
	},
};